﻿using System.Text;
using MoXAML.Infrastructure;
using EnvDTE;

namespace MoXAML.PowerToys.Classic
{
    /// <summary>
    /// The comment command is used to comment out blocks of XAML. This goes above and beyond the Visual Studio
    /// XAML commenting, which has problems when you try to comment out previously commented out code.
    /// </summary>
    /// <remarks><para>Revision history:</para>
    /// <para>Based on chaiguy's feedback, commenting now supports adding in empty comment blocks 
    /// (suitable for adding new comments).</para>
    /// <para>The commenting now copes with VS inserted comments, by converting them to /* and */ items
    /// when a new comment is performed on it.</para>
    /// </remarks>
    public class CommentCommand : CommentBase
    {
        public CommentCommand() : base()
        {
            this.CommandName = "CommandCommentXaml";
            this.Caption = "Comment XAML";
        }

        public override void Execute()
        {
            TextSelection selection = Application.TextSelection();
            if (selection == null) return;

            StringBuilder sb = new StringBuilder();
            string selText = selection.Text.Replace(OpenComment, OpenInnerComment).Replace(CloseComment, CloseInnerComment);
            bool isAttribute = false;
            sb.AppendFormat("{0}{1}{2}", OpenComment, selText, CloseComment);

            EditPoint pt = selection.TopPoint.CreateEditPoint();
            if (!isAttribute)
            {
                if (!string.IsNullOrWhiteSpace(selection.Text))
                {
                    selection.ReplacePattern(selection.Text, sb.ToString(), (int)vsFindOptions.vsFindOptionsMatchCase);
                }
                else
                {
                    selection.Insert(sb.ToString(), (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                }
            }
            else
            {
                selection.ReplacePattern(selection.Text, string.Empty, (int)vsFindOptions.vsFindOptionsMatchCase);
            }
        }
    }
}
